package com.motu.monstercity.server.game.logic;

import com.motu.monstercity.module.common.network.ResponseUtils;
import com.motu.monstercity.protocol.CmdEnum;
import com.motu.monstercity.protocol.CsGameSystem;
import com.motu.monstercity.protocol.CsGameSystem.CSGameSystemRedPointResponse;
import com.motu.monstercity.server.game.commondata.act.ActWord;
import com.motu.monstercity.server.game.commondata.mail.MailConstant;
import com.motu.monstercity.server.game.commondata.system.SystemConstant;
import com.motu.monstercity.server.game.commondata.system.SystemWord;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.model.EntityManager;
import com.motu.vertx.module.utility.model.Model;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;

import java.util.ArrayList;
import java.util.List;

public class MailManager extends BagUserData {
    // 根据userid和dbid获取usermail对象
    public static UserMail getUserMail(long userId, long dbid) {
        return (UserMail) EntityManager.getEntity(UserMail.class, userId, dbid);
    }

    // 获取邮件列表
    public static List<UserMail> getUserMailList(long userId) {
        List<UserMail> list = new ArrayList<>();
        for (Model model : EntityManager.getEntityList(UserMail.class, userId)) {
            UserMail entity = (UserMail) model;
            list.add(entity);
        }
        return list;
    }

    /**
     * 标题内容都不需要进行字符串替换 根据titleId,contentId,发送系统邮件 titleId,contentId 是固定的，在mailconstant定义，策划配置在common库的system_word表
     */
    public static void sendSystemMail(long userId, int titleId, int contentId, List<RewardItem> list, int logType) {
        String item = "";
        if (list != null && list.size() > 0) {
            item = getMailItem(list);
        }
        sendMail(userId, titleId, contentId, logType, item, MailConstant.MAIL_ID_TYPE_SYSTEM, "", "");
    }

    /**
     * 目前只支持替换邮件内容，后续邮件标题也要进行替换的话，需要另外写新的方法 根据titleId,contentId,发送系统邮件 titleId,contentId 是固定的，在mailconstant定义，策划配置在common库的system_word表
     * @param userId
     * @param titleId  定义在mailconstant
     * @param contentId 定义在mailconstant
     * @param list
     * @param logType
     * @param params 需要替换成的字符串，
     */
    public static void sendSystemMailReplaceContent(long userId, int titleId, int contentId, List<RewardItem> list, int logType, Object... params) {
        String item = "";
        if (list != null && list.size() > 0) {
            item = getMailItem(list);
        }
        String contentReplace = "";
        if (params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                String ss = String.valueOf(params[i]);
                if (!Tool.isEmpty(ss)) {
                    contentReplace += params[i];
                }
                if (i < params.length - 1) {
                    contentReplace += "|";
                }
            }
        }

        sendMail(userId, titleId, contentId, logType, item, MailConstant.MAIL_ID_TYPE_SYSTEM, "", contentReplace);
    }

    /**
     * 根据titleId,contentId,发送维护补偿活动邮件 文字内容从server库act_word表读取的。titleId,contentId 不是固定的，表自增生成的。用这个方法
     */
    public static void sendActMail(long userId, int titleId, int contentId, List<RewardItem> list, int logType) {
        String item = "";
        if (list != null && list.size() > 0) {
            item = getMailItem(list);
        }
        sendMail(userId, titleId, contentId, logType, item, MailConstant.MAIL_ID_TYPE_ACT_WORD, "", "");//维护补偿活动 邮件没有占位符需要替代
    }

    /**
     * 后台发送邮件 文字内容从活动文字act_word表读取的。只有运营在后台给玩家发送邮件时会用
     * @param userId
     * @param titleId
     * @param contentId
     * @param item
     * @param logType
     * @param mailType
     */
    public static void sendWebMail(long userId, long titleId, long contentId, String item, int logType, byte mailType) {
        int wordType = MailConstant.MAIL_ID_TYPE_ACT_WORD;
        String title = makeWordIdString(wordType, titleId);
        String content = makeWordIdString(wordType, contentId);
        UserMail usermail = new UserMail(userId, mailType, title, content, logType, item, "", "");// 后台发送的邮件没有占位符需要替代
        usermail.doCreate();
        sendMailRedPrompt(userId);
    }





    /**
     * 只存储文字id,
     * @param wordType mailconstant 的 MAIL_ID_TYPE_SYSTEM or MAIL_ID_TYPE_ACT
     * @param wordId system_word表的id 或是act_word表的id
     * @return
     */
    public static String makeWordIdString(int wordType, long wordId) {
        return "&" + wordType + "|" + wordId + "&";
    }


    // 根据语言获取对应的文本内容
    public static String takeWordSting(String wordIdString, int language, String replaceStr) {
        String ss = wordIdString.replace("&", "");// 去掉头尾的&
        String[] array = ss.split("\\|");// 特殊字符| 需要进行转义
        int wordType = Integer.parseInt(array[0]);//mailconstant 的 MAIL_ID_TYPE_SYSTEM or MAIL_ID_TYPE_ACT
        int wordId = Integer.parseInt(array[1]);
        Object[] replaceParams = getReplaceParam(replaceStr);
        if (wordType == MailConstant.MAIL_ID_TYPE_ACT_WORD) {
            return GameDataManager.getActWord(wordId, language, replaceParams); // 进行占位符替代
        } else {// 从system_word读取
            return GameDataManager.getSystemWord(wordId, language, replaceParams); // 进行占位符替代
        }
    }

    // 占位符替代文本转化成 Object[], 77|88|99
    private static Object[] getReplaceParam(String replaceStr) {
        Object[] replaceParam = new Object[0];
        if (Tool.isEmpty(replaceStr)) {
            return replaceParam;
        }
        try {
            String[] array = replaceStr.split("\\|");// 特殊字符| 需要进行转义
            int size = array.length;
            replaceParam = new Object[size];
            for (int i=0; i<size; i++) {
                replaceParam[i] = array[i];
            }
            return replaceParam;
        } catch (Exception e) {
        }
        return replaceParam;
    }

    /**
     * 根据titleId,contentId,发送邮件，私有方法，一般情况下只需用sendSystemMail方法
     * @param titleId system_word表的id 或是act_word表的id
     * @param contentId system_word表的id 或是act_word表的id
     * @param titleReplace 标题占位符的替代文字
     * @param contentReplace 邮件内容的占位符的替代文字
     * @param wordType  mailconstant 的 MAIL_ID_TYPE_SYSTEM or MAIL_ID_TYPE_ACT
     */
    private static void sendMail(long userId, int titleId, int contentId, int logType, String item, int wordType, String titleReplace, String contentReplace) {
        String title = makeWordIdString(wordType, titleId);
        String content = makeWordIdString(wordType, contentId);
        byte mailType = 0;// 默认普通邮件
        if (wordType == MailConstant.MAIL_ID_TYPE_ACT_WORD) {
            ActWord actWord = GameDataManager.getActWord(titleId);
            if (actWord != null) {
                mailType = actWord.getType();
            }
        } else {
            SystemWord systemWord = GameDataManager.getSystemWord(titleId);
            if (systemWord != null) {
                mailType = systemWord.getType();
            }
        }
        UserMail usermail = new UserMail(userId, mailType, title, content, logType, item, titleReplace, contentReplace);
        usermail.doCreate();
        sendMailRedPrompt(userId);
    }

    // 推送红点提示
    private static void sendMailRedPrompt(long userId) {
        CSGameSystemRedPointResponse.Builder builder = CSGameSystemRedPointResponse.newBuilder();
        builder.setPromptType(SystemConstant.RED_POINT_TYPE_MAIL);
        CsGameSystem.RedPoint_Mail.Builder redPointMail = CsGameSystem.RedPoint_Mail.newBuilder();
        redPointMail.setNewMail(true);
        builder.setMail(redPointMail);
        JsonObject jsonObject = ResponseUtils.getRedpointResponseData( builder.build().toByteArray());
        GameUser.pushToUser(userId, jsonObject);
    }

    // 邮件道具的字符串
    public static String getMailItem(List<RewardItem> list) {
        JsonArray jsonArray = new JsonArray();
        for (RewardItem rewardItem : list) {
            JsonObject obj = new JsonObject();
            obj.put("id", rewardItem.getItemId());
            obj.put("num", rewardItem.getItemNum());
            jsonArray.add(obj);
        }
        return jsonArray.toString();
    }

    // [{"id":100001,"num":100}] 格式的字符串转成
    public static List<RewardItem> takeRewardItem(String rewardStr) {
        List<RewardItem> list = new ArrayList<>();
        if (!Tool.isEmpty(rewardStr)) {
            try {
                JsonArray jsonArray = new JsonArray(rewardStr);
                for (int i=0; i<jsonArray.size(); i++) {
                    JsonObject obj = jsonArray.getJsonObject(i);
                    RewardItem rewardItem = new RewardItem(obj.getInteger("id"), obj.getLong("num"));
                    list.add(rewardItem);
                }
            } catch (Exception e) {
            }
        }
        return list;
    }

    // 邮件红点
    public static boolean checkRedPoint(CSGameSystemRedPointResponse.Builder builder, UserInfo userInfo){
        List<UserMail> list = getUserMailList(userInfo.getId());
        CsGameSystem.RedPoint_Mail.Builder redPointMail = CsGameSystem.RedPoint_Mail.newBuilder();
        for (UserMail userMail : list) {
            if (!userMail.isRead()) {// 有未查看的邮件就提示红点
                redPointMail.setNewMail(true);
                builder.setMail(redPointMail);
                return true;
            }
        }
        return false;
    }
}
